package cn.billy.basic.service.impl;

import cn.billy.basic.constant.BaseConstants;
import cn.billy.basic.dto.LoginDto;
import cn.billy.basic.dto.RegisterDto;
import cn.billy.basic.dto.WechatDto;
import cn.billy.basic.exception.BusinessException;
import cn.billy.basic.jwt.JwtUtils;
import cn.billy.basic.jwt.RsaUtils;
import cn.billy.basic.jwt.UserInfo;
import cn.billy.basic.service.ILoginService;
import cn.billy.basic.utils.AjaxResult;
import cn.billy.basic.utils.HttpUtil;
import cn.billy.basic.utils.MD5Utils;
import cn.billy.basic.utils.StrUtils;
import cn.billy.system.domain.Menu;
import cn.billy.system.mapper.MenuMapper;
import cn.billy.system.mapper.PermissionMapper;
import cn.billy.user.domain.Logininfo;
import cn.billy.user.domain.User;
import cn.billy.user.domain.Wxuser;
import cn.billy.user.mapper.LogininfoMapper;
import cn.billy.user.mapper.UserMapper;
import cn.billy.user.mapper.WxuserMapper;
import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.security.PrivateKey;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

import static cn.billy.basic.constant.BaseConstants.WeChatConstant.APPID;
import static cn.billy.basic.constant.BaseConstants.WeChatConstant.SECRET;

@Service
public class LoginServiceImpl implements ILoginService {

    @Autowired
    private LogininfoMapper logininfoMapper;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private WxuserMapper wxuserMapper;

    @Autowired
    private UserMapper userMapper;

    @Value("${jwt.rsa.pri}")
    private String jwtRsaPri;

    @Autowired
    private PermissionMapper permissionMapper;

    @Autowired
    private MenuMapper menuMapper;

    /*@Override
    public HashMap<String, Object> account(LoginDto loginDto) {
        String username = loginDto.getUsername();
        String password = loginDto.getPassword();
        Integer type = loginDto.getType();
        System.out.println(loginDto);
        // 判断非空
        if (StringUtils.isEmpty(username)
                || StringUtils.isEmpty(password)
                || StringUtils.isEmpty(type)){
            throw new BusinessException("参数错误请重新输入");
        }
        // 根据username，type两个参数来查询到logininfo里面对应的值
        Logininfo logininfo = logininfoMapper.loadByUsernameAndType(username,type);
        // 如果为空就说明没有这个员工
        if (logininfo == null){
            throw new BusinessException("账号和密码错误，请重新输入！");
        }
        // 将传进来的参数的密码重新加盐加密进行比较

        String s = logininfo.getSalt();
        String md5 = MD5Utils.encrypByMd5(logininfo.getSalt() + password);
        System.out.println(logininfo.getSalt());
        System.out.println(md5);
        // 如果不对，就说明密码输入错误
        if (!logininfo.getPassword().equals(md5)){
            throw new BusinessException("账号和密码错误，请重新输入！");
        }
        // 生成UUID作为token
        String token = UUID.randomUUID().toString();
        // 将token和logininfo转入redis中，设置有效时间为30分钟
        redisTemplate.opsForValue().set(token,logininfo,30, TimeUnit.MINUTES);
        // 将盐和密码进行隐藏，直接给他赋值一个空字符串
        logininfo.setSalt("");
        logininfo.setPassword("");
        // 创建一个HashMap
        HashMap<String, Object> map = new HashMap<>();
        // 将token和logininfo存放在map中
        map.put("token",token);
        map.put("logininfo",logininfo);
        return map;
    }*/

    @Override
    public HashMap<String, Object> account(LoginDto loginDto) {
        String username = loginDto.getUsername();
        String password = loginDto.getPassword();
        Integer type = loginDto.getType();
        System.out.println(loginDto);
        // 判断非空
        if (StringUtils.isEmpty(username)
                || StringUtils.isEmpty(password)
                || StringUtils.isEmpty(type)){
            throw new BusinessException("参数错误请重新输入");
        }
        // 根据username，type两个参数来查询到logininfo里面对应的值
        Logininfo logininfo = logininfoMapper.loadByUsernameAndType(username,type);
        // 如果为空就说明没有这个员工
        if (logininfo == null){
            throw new BusinessException("账号和密码错误，请重新输入！");
        }
        // 将传进来的参数的密码重新加盐加密进行比较

        String md5 = MD5Utils.encrypByMd5(logininfo.getSalt() + password);
        // 如果不对，就说明密码输入错误
        if (!logininfo.getPassword().equals(md5)){
            throw new BusinessException("账号和密码错误，请重新输入！");
        }

        return sb(logininfo);
    }

    public HashMap<String, Object> sb(Logininfo logininfo){
        // 1 获取token
        PrivateKey privateKey = RsaUtils.getPrivateKey(JwtUtils.class.getClassLoader().getResource(jwtRsaPri).getFile());
        UserInfo userInfo = new UserInfo();
        HashMap<String, Object> map = new HashMap<>();
        if (logininfo.getType() == 0){
            List<String> permissions = permissionMapper.loadOwnPermissionByLogininId(logininfo.getId());
            System.out.println("333333"+permissions);
            List<Menu> menus = menuMapper.loadOwnMenuByLogininfoId(logininfo.getId());
            userInfo.setPermissions(permissions);
            userInfo.setMenus(menus);
            map.put("permissions",permissions);
            map.put("menus",menus);
        }
        userInfo.setLogininfo(logininfo);
        String token = JwtUtils.generateTokenExpireInMinutes(userInfo, privateKey, 600);
        // 将盐和密码进行隐藏，直接给他赋值一个空字符串
        logininfo.setSalt("");
        logininfo.setPassword("");
        // 创建一个HashMap

        // 将token和logininfo存放在map中
        map.put("token",token);
        map.put("logininfo",logininfo);
        return map;
    }


    @Override
    public AjaxResult wechat(WechatDto wechatDto) {
        String code = wechatDto.getCode();
        if (StringUtils.isEmpty(code)){
            throw new BusinessException("参数为空，请重新输入");
        }
        String tokenUrl = BaseConstants.WeChatConstant.TOKEN_URL
                .replace("APPID",APPID)
                .replace("SECRET",SECRET)
                .replace("CODE", code);
        String jsonStr = HttpUtil.httpGet(tokenUrl);
        JSONObject jsonObject = JSONObject.parseObject(jsonStr);
        String accessToken = jsonObject.getString("access_token");
        String openId = jsonObject.getString("openid");
        Wxuser wxUser = wxuserMapper.getByOpenId(openId);
        if (wxUser != null && wxUser.getUserId() != null){
            User byId = userMapper.getById(wxUser.getUserId());
            Logininfo logininfo = logininfoMapper.getByUserId(byId.getLogininfoId());
            HashMap<String, Object> map = sb(logininfo);
            return AjaxResult.me().setResultObj(map);
        }
        StringBuffer stringBuffer = new StringBuffer()
                .append("?accessToken=")
                .append(accessToken)
                .append("&openId=")
                .append(openId);
        return AjaxResult.me().setSuccess(false).setResultObj(stringBuffer);
    }

    @Override
    public HashMap<String, Object> binder(WechatDto wechatDto) {
        // 1.非空校验
        String verifyCode = wechatDto.getVerifyCode();
        String phone = wechatDto.getPhone();
        String accessToken = wechatDto.getAccessToken();
        String openId = wechatDto.getOpenId();
        if (StringUtils.isEmpty(verifyCode)
                || StringUtils.isEmpty(phone)
                || StringUtils.isEmpty(accessToken)
                || StringUtils.isEmpty(openId)){
            throw new BusinessException("参数异常！");
        }
        // 2.手机验证码校验
        // 1.为空校验
        String phoneCodeKey = BaseConstants.VerifyCodeConstant.BUSINESS_BINDER_PREFIX + phone;
        Object phoneCodeValueRedis = redisTemplate.opsForValue().get(phoneCodeKey);
        // 3.判断验证码是否正确
        String phoneCode = phoneCodeValueRedis.toString().split(":")[1];
        if (!phoneCode.equalsIgnoreCase(verifyCode)){
            throw new BusinessException("手机验证码错误，请重新输入！");
        }
        // 3.根据手机号查询用户是否存在
        User user = userMapper.getByPhone(phone);
        // 3.1.不存在：初始化user&logininfo并保存
        Logininfo logininfo = null;
        if (user == null){
            user = smsCodeDto2User(phone);
            logininfo = user2Logininfo(user);
            logininfoMapper.add(logininfo);
            user.setLogininfoId(logininfo.getId());
            userMapper.add(user);
        }else {// 3.2.存在：查询Logininfo
            logininfo = logininfoMapper.getByUserId(user.getLogininfoId());
        }
        // 4.根据前端传递的accessToken&openId查询微信用户基本信息
        String wxUserUrl = BaseConstants.WeChatConstant.WXUSER_URL
                .replace("ACCESS_TOKEN", accessToken)
                .replace("OPENID", openId);
        String wxUserStr = HttpUtil.httpGet(wxUserUrl);
        // 5.通过JSONObject方法将JSON字符串转换为指定对象
        Wxuser wxuser = JSONObject.parseObject(wxUserStr, Wxuser.class);
        // 5.保存wxUser对象，并且需要设置userId字段为user对象的主键
        wxuser.setUserId(user.getId());
        wxuserMapper.add(wxuser);
        // 6.返回成功登录map

        return sb(logininfo);
    }

    private Logininfo user2Logininfo(User user) {
        Logininfo logininfo = new Logininfo();
        BeanUtils.copyProperties(user,logininfo);
        logininfo.setType(1);
        return logininfo;

    }

    private User smsCodeDto2User(String phone) {
        User user = new User();
        user.setUsername(phone);
        user.setPhone(phone);
        String salt = StrUtils.getComplexRandomString(32);
        String saltPassword = MD5Utils.encrypByMd5(salt + "1");
        user.setPassword(saltPassword);
        user.setSalt(salt);
        // 此处最好给用户发个短信，告知他初始密码是多少
        return user;
    }


}
